<template>
    <el-container class="app-container" :class="{ 'dark-mode': isDarkMode }">
        <!-- 顶部导航栏 -->
        <el-header class="app-header">
            <div class="header-left">
                <el-button
                    class="menu-toggle-btn"
                    size="small"
                    circle
                    @click="sidebarVisible = !sidebarVisible"
                    :plain="true"
                    type="info"
                    v-show="isMobile"
                >
                    <i class="bi bi-list"></i>
                </el-button>
                <router-link to="/home/dashboard" class="app-logo">
                    物业管理系统
                </router-link>
            </div>

            <div class="header-right">
                <el-tooltip content="切换主题" placement="bottom">
                    <el-button
                        size="small"
                        circle
                        @click="toggleTheme"
                        :type="isDarkMode ? 'warning' : 'primary'"
                        class="theme-toggle-btn"
                    >
                        <i class="bi bi-palette"></i>
                    </el-button>
                </el-tooltip>

                <el-tooltip content="帮助文档" placement="bottom">
                    <el-button size="small" circle type="info" @click="goToHelp">
                        <i class="bi bi-question-circle-fill"></i>
                    </el-button>
                </el-tooltip>

                <!-- 用户下拉菜单 -->
                <el-dropdown class="user-dropdown" trigger="click" @command="handleDropdownCommand">
                    <span class="el-dropdown-link">
                        <span class="user-name">{{ user.name || '未登录' }}</span>
                    </span>
                    <template #dropdown>
                        <el-dropdown-menu>
                            <el-dropdown-item command="logout" divided class="text-danger">退出登录</el-dropdown-item>
                        </el-dropdown-menu>
                    </template>
                </el-dropdown>
            </div>
        </el-header>

        <el-container>
            <!-- 侧边栏 -->
            <transition name="slide-in">
                <el-aside v-if="!isMobile || sidebarVisible" class="app-sidebar" width="250px">
                    <el-menu
                        class="custom-menu"
                        unique-opened
                        :background-color="isDarkMode ? 'var(--color-sidebar-bg-dark)' : 'var(--color-sidebar-bg)'"
                        text-color="var(--color-text-light)"
                        active-text-color="#ffd04b"
                        :default-active="activeMenu"
                        router
                    >
                        <el-sub-menu index="property-menu">
                            <template #title>
                                <i class="bi bi-geo-alt-fill"></i>
                                <span>物业管理</span>
                            </template>
                            <el-menu-item index="/home/properties">
                                <router-link to="/home/properties" class="no-underline">楼盘信息</router-link>
                            </el-menu-item>
                            <el-menu-item index="/home/units">
                                <router-link to="/home/units" class="no-underline">单元管理</router-link>
                            </el-menu-item>
                        </el-sub-menu>

                        <el-sub-menu index="announcement-menu">
                            <template #title>
                                <i class="bi bi-megaphone-fill"></i>
                                <span>公告管理</span>
                            </template>
                            <el-menu-item index="/home/announcements">
                                <router-link to="/home/announcements" class="no-underline">公告列表</router-link>
                            </el-menu-item>
                        </el-sub-menu>

                        <el-sub-menu index="activity-menu">
                            <template #title>
                                <i class="bi bi-bar-chart-line-fill"></i>
                                <span>动态管理</span>
                            </template>
                            <el-menu-item index="/home/activities">
                                <router-link to="/home/activities" class="no-underline">动态列表</router-link>
                            </el-menu-item>
                        </el-sub-menu>

                        <el-sub-menu index="system-menu">
                            <template #title>
                                <i class="bi bi-gear-fill"></i>
                                <span>系统设置</span>
                            </template>
                            <el-menu-item index="/home/user_management">
                                <router-link to="/home/user_management" class="no-underline">用户管理</router-link>
                            </el-menu-item>
                        </el-sub-menu>
                    </el-menu>
                </el-aside>
            </transition>

            <el-main class="app-main">
                <div class="page-header">
                    <h2 class="page-title">{{ currentTitle }}</h2>
                </div>

                <transition name="fade">
                    <router-view class="component-view" />
                </transition>
            </el-main>
        </el-container>
    </el-container>
</template>

<script>
import { onMounted, ref, computed } from 'vue';
import axios from 'axios';
import { useRoute, useRouter } from 'vue-router';

export default {
    name: 'Home',
    setup() {
        const router = useRouter();
        const route = useRoute();

        const token = ref(localStorage.getItem('token'));
        const user = ref({
            name: '未登录',
            phone: '',
            role: '',
            unit_number: '',
            floor: '',
            roomCount: 0,
        });
        const isDarkMode = ref(false);
        const sidebarVisible = ref(true);
        const activeMenu = ref(route.path); // 初始化为当前路由路径

        const componentTitles = {
            '/home/dashboard': '欢迎来到物业后台管理系统',
            '/home/properties': '楼盘信息管理',
            '/home/units': '单元管理',
            '/home/announcements': '公告列表',
            '/home/activities': '动态列表',
            '/home/user_management': '用户管理',
        };

        const currentTitle = computed(() => componentTitles[activeMenu.value] || '物业后台管理系统');

        const fetchUserData = async () => {
            if (!token.value) {
                handleLogout();
                return;
            }
            try {
                const response = await axios.get('http://localhost:3008/users/me', {
                    headers: { Authorization: `Bearer ${token.value}` },
                });
                if (response.data && response.data.data) {
                    const userData = response.data.data;
                    user.value.name = userData.name || '未登录';
                    user.value.phone = userData.phone || '';
                    user.value.role = userData.role || '';

                    if (userData.unit_id) {
                        const unitResponse = await axios.get(`http://localhost:3008/units/${userData.unit_id}`, {
                            headers: { Authorization: `Bearer ${token.value}` },
                        });
                        if (unitResponse.data && unitResponse.data.data) {
                            const unitData = unitResponse.data.data;
                            user.value.unit_number = unitData.unit_number || '';
                            user.value.floor = unitData.floor || 0;
                            user.value.roomCount = unitData.room_count || 0;
                        }
                    }
                }
            } catch (error) {
                console.error('用户信息加载失败:', error);
                if (error.response && error.response.status === 401) {
                    handleLogout();
                }
            }
        };

        const handleLogout = () => {
            localStorage.removeItem('token');
            localStorage.removeItem('user');
            router.push('/login');
        };

        const toggleTheme = () => {
            isDarkMode.value = !isDarkMode.value;
            localStorage.setItem('isDarkMode', isDarkMode.value);
        };

        const goToHelp = () => {
            window.open('/help', '_blank');
        };

        const handleDropdownCommand = (command) => {
            if (command === 'logout') {
                handleLogout();
            }
        };

        const updateActiveMenu = () => {
            activeMenu.value = route.path;
        };

        onMounted(() => {
            fetchUserData();
            // 设置初始主题模式
            const darkMode = localStorage.getItem('isDarkMode') === 'true';
            isDarkMode.value = darkMode;

            window.addEventListener('resize', () => {
                sidebarVisible.value = window.innerWidth >= 768;
            });

            // 监听路由变化以更新 activeMenu 和 currentTitle
            router.afterEach(() => {
                updateActiveMenu();
            });
        });

        return {
            token,
            currentTitle,
            user,
            isDarkMode,
            toggleTheme,
            goToHelp,
            isMobile: computed(() => window.innerWidth < 768),
            sidebarVisible,
            handleDropdownCommand,
            activeMenu,
        };
    },
};
</script>

<style>
:root {
    --color-bg-light: #f5f7fa;
    --color-bg-dark: #2c3e50;
    --color-header-bg: #34495e;
    --color-header-bg-dark: #1c2833;
    --color-text-light: #ffffff;
    --color-sidebar-bg: #34495e;
    --color-sidebar-bg-dark: #2c3e50;
    --color-highlight: #ffd04b;
}

.app-container {
    height: 100vh;
    display: flex;
    flex-direction: column;
}

.app-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    background-color: var(--color-header-bg);
    color: var(--color-text-light);
    padding: 0 1.5rem;
    height: 60px;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.header-left {
    display: flex;
    align-items: center;
}

.menu-toggle-btn {
    margin-right: 1rem;
}

.app-logo {
    font-size: 22px;
    font-weight: 600;
    color: var(--color-highlight);
    cursor: pointer;
    transition: color 0.3s;
    text-decoration: none;
}

.app-logo:hover {
    color: #f39c12;
}

.header-right {
    display: flex;
    align-items: center;
    gap: 0.8rem;
}

.theme-toggle-btn,
.user-dropdown {
    margin-right: 0.8rem;
}

.user-name {
    color: var(--color-text-light);
    font-weight: 500;
}

.el-dropdown-menu {
    z-index: 2000 !important;
}

.app-sidebar {
    background-color: var(--color-sidebar-bg);
    color: var(--color-text-light);
}

.app-main {
    background-color: var(--color-bg-light);
    padding: 20px;
    flex-grow: 1;
    overflow-y: auto;
}

.page-header {
    margin-bottom: 20px;
}

.page-title {
    font-size: 24px;
    font-weight: 600;
}

.custom-menu .el-menu-item,
.custom-menu .el-sub-menu__title {
    font-size: 16px;
}

.no-underline {
    text-decoration: none;
}

/* Dark Mode */
.dark-mode {
    background-color: var(--color-bg-dark);
    color: var(--color-text-light);
}

.dark-mode .app-header {
    background-color: var(--color-header-bg-dark);
}

.dark-mode .app-sidebar {
    background-color: var(--color-sidebar-bg-dark);
}

.dark-mode .app-main {
    background-color: #1e272e;
}

.dark-mode .el-menu {
    background-color: var(--color-sidebar-bg-dark);
}

.dark-mode .el-menu-item, 
.dark-mode .el-sub-menu__title {
    color: var(--color-text-light) !important;
}

.slide-in-enter-active, .slide-in-leave-active {
    transition: all 0.3s ease;
}
.slide-in-enter-from, .slide-in-leave-to {
    transform: translateX(-100%);
    opacity: 0;
}

.fade-enter-active, .fade-leave-active {
    transition: opacity 0.5s;
}
.fade-enter-from, .fade-leave-to {
    opacity: 0;
}

/* 响应式调整 */
@media (max-width: 767px) {
    .app-sidebar {
        position: absolute;
        z-index: 1000;
        height: 100%;
    }
}
</style>
